package com.xk.school_device.utlis;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import com.xk.school_device.config.MinioConfig;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.StatObjectArgs;
import io.minio.errors.MinioException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;


import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Component
@Slf4j
public class MinioUtil {
    @Autowired
    private MinioConfig prop;

    @Resource
    private MinioClient minioClient;

    public String upload(MultipartFile file) throws MinioException {
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            throw new RuntimeException("File name cannot be blank");
        }
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM/dd")) + "/" + fileName;
        try {
            PutObjectArgs objectArgs = PutObjectArgs.builder()
                    .bucket(prop.getBucketName())
                    .object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build();
            minioClient.putObject(objectArgs);
            // Construct the file URL
            String fileUrl = String.format("%s/%s/%s", prop.getUrl(), prop.getBucketName(), objectName);  //  prop.getUrl() https://minio.xk021104.cn /   prop.getBucketName() // images   objectName 文件名字     //    https://minio.xk021104.cn/images/文件名字
            return fileUrl;
        } catch (MinioException e) {
//            log.error("Error uploading file: {}", e.getMessage(), e);
            throw e;
        } catch (Exception e) {
//            log.error("Unexpected error uploading file", e);
            throw new MinioException("Unexpected error uploading file");
        }
    }
    public void delete(String objectName) throws MinioException {
        try {
            String bucketName = prop.getBucketName();
//            log.info("准备删除对象: {}", objectName);

            // 确保传递的 objectName 是相对路径
            String baseUrl = prop.getUrl() + bucketName + "/";
            String relativeObjectName = objectName.startsWith(baseUrl) ?
                    objectName.substring(baseUrl.length()) :
                    objectName;

            // 验证对象是否存在
            StatObjectArgs statObjectArgs = StatObjectArgs.builder()
                    .bucket(bucketName)
                    .object(relativeObjectName)
                    .build();
            minioClient.statObject(statObjectArgs);

            // 删除对象
            RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder()
                    .bucket(bucketName)
                    .object(relativeObjectName)
                    .build();
            minioClient.removeObject(removeObjectArgs);
//            log.info("成功删除对象: {}", relativeObjectName);
        } catch (MinioException e) {
//            log.error("删除失败: {}", e.getMessage(), e);
            throw e;
        } catch (Exception e) {
//            log.error("删除失败", e);
            throw new MinioException("删除失败");
        }
    }
}
